package fy.form.listen.bean;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

public abstract class JSONBean {

	public String toString() {

		Field[] fields = this.getClass().getDeclaredFields();
		JSONObject jo = new JSONObject();

		if (fields != null) {
			try {
				for (int i = 0, length = fields.length; i < length; i++) {
					fields[i].setAccessible(true);
					Object value = fields[i].get(this);
					fields[i].setAccessible(false);
					String name = fields[i].getName();
					if (value instanceof List) {
						List<?> list = (List<?>) value;
						for (int j = 0, size = list.size(); j < size; j++) {
							jo.append(name, list.get(j).toString());
						}
					} else if (value instanceof Map) {
						Map<?,?> map = (Map<?,?>) value;
						JSONObject child = new JSONObject();
						for (Iterator<?> iter = map.keySet().iterator(); iter
								.hasNext();) {
							Object key = iter.next();
							child.put(key.toString(), map.get(key).toString());
						}
						jo.put(name, child);
					} else {
						jo.put(name, value);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return jo.toString();
	}
}
